/*
 * Copyright (c) 2023-2024 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.module.dict.api.configuration;

import org.elsfs.cloud.common.annotations.DictionaryTranslation;
import org.elsfs.cloud.common.core.aop.AnnotationAdvisor;
import org.elsfs.cloud.module.dict.api.aop.DictMethodInterceptor;
import org.elsfs.cloud.module.dict.api.service.DictService;
import org.springframework.aop.Advisor;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Role;

/**
 * 字典配置相关
 *
 * @author zeng
 */
@AutoConfiguration
public class DictConfiguration {

  /**
   * 创建 DictMethodInterceptor 实例。 该方法只有在以下条件同时满足时才会被调用： 1. DictService 类已存在一个bean实例。 2. 缺少名为
   * DictMethodInterceptor 的bean实例。
   *
   * @implNote dictService 字典服务接口的实例，用于字典数据的查询。
   * @return DictMethodInterceptor 的新实例，用于拦截器链中进行字典数据的处理。
   */
  @Bean
  @Role(BeanDefinition.ROLE_SUPPORT)
  @ConditionalOnBean(value = DictService.class)
  @ConditionalOnMissingBean(DictMethodInterceptor.class)
  public DictMethodInterceptor dictMethodInterceptor() {
    return new DictMethodInterceptor();
  }

  /**
   * 创建并返回一个注释类型的Advisor Bean，它基于DictionaryTranslation注解提供拦截器功能。
   * 这个方法的作用是启用对标注了DictionaryTranslation注解的方法的拦截，具体的拦截逻辑由传入的DictMethodInterceptor实现。
   *
   * @implSpec dictMethodInterceptor 拦截器实例，负责处理注解方法的拦截逻辑。
   * @return 返回一个配置好的Advisor实例，它包含了注解拦截器的配置信息。
   */
  @Bean
  @Role(BeanDefinition.ROLE_SUPPORT)
  @ConditionalOnBean(DictMethodInterceptor.class)
  public Advisor dictionaryAnnotationAdvisor() {
    // 创建AnnotationAdvisor，将拦截器和注解绑定
    return new AnnotationAdvisor(new DictMethodInterceptor(), DictionaryTranslation.class);
  }
}
